from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
from polls import models
from django.core import serializers
from django.db import connection
import json
import time
import hashlib
import random

@ensure_csrf_cookie #token令牌访问
#登录
def login(request):
    #获取cursor对象 进行sql语句的操作
    cursor = connection.cursor()
    if request.method == "POST":
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        m = hashlib.md5() # 创建md5哈希对象
        b = password.encode(encoding='utf-8') #将密码替换成字节
        m.update(b) #将密码变为哈希加密保存
        str_md5 = m.hexdigest() # 获取哈希值的十六进制字符串表示
        user_list = models.SMember.objects.filter(phone=phone,password=str_md5)
        # 查找用户错误
        if len(user_list) == 0:
            ret = {"code": 2, 'msg': '账号或密码错误'}
            return HttpResponse(json.dumps(ret), content_type="application/json")
        if user_list[0].status == 0:
            ret = {"code": 2, 'msg': '该账号已被封号，请联系管理员'}
            return HttpResponse(json.dumps(ret), content_type="application/json")
        now = time.time()
        ip = request.META['REMOTE_ADDR']
        sql = 'insert into s_login_log(id,nickname,phone,ip,createtime) values(%s,%s,%s,%s,%s)'
        cursor.execute(sql,[user_list[0].keyid,user_list[0].nickname,user_list[0].phone,ip,now])
        num = user_list[0].login_num + 1
        models.SMember.objects.filter(phone=phone).update(login_num=num)
        request.session['user_id'] = user_list[0].keyid
        request.session['user_type'] = user_list[0].type
        request.session['active_code'] = user_list[0].active_code
        ret = {"code": 1, 'msg': "登录成功"}
        return HttpResponse(json.dumps(ret), content_type="application/json")
    return  render(request,'login.html')
# 注册
def reg(request):
    cursor = connection.cursor()
    if request.method == 'POST':
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        yzm = request.POST.get("yzm")
        recommend = request.POST.get("recommend")
        realname = request.POST.get("realname")
        cursor.execute("select * from s_member where phone=%s",[phone])
        rows = cursor.fetchone()
        if rows:
            ret = {"code": 2, 'msg': '手机号已经被注册了'}
            return HttpResponse(json.dumps(ret), content_type="application/json")



